package com.burgeon.backend.Util.ImageSynthesis;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageSynthesis {
    /**
     *
     * @Title: 构造图片
     * @Description: 生成水印并返回java.awt.image.BufferedImage
     * @param file
     *            源文件(图片)
     * @param head
     *            水印文件(图片) 头像
     * @param QRcode
     *            水印文件(图片) 二维码
     * @return BufferedImage
     * @throws IOException
     */
    public  BufferedImage watermark(File file, File head,File QRcode,String emp,String store) throws IOException {
        // 获取底图
        BufferedImage buffImg = ImageIO.read(file);
        // 获取层图
        BufferedImage headImg = ImageIO.read(head);
        BufferedImage QRcodeImg = ImageIO.read(QRcode);

        // 创建Graphics2D对象，用在底图对象上绘图
        Graphics2D g2d = buffImg.createGraphics();
        // 在图形和图像中实现混合和透明效果
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1f));
        // 绘制

        g2d.drawImage(headImg, 40, 40, 100, 100, null);
        g2d.drawImage(QRcodeImg, 75, 210, 450, 450, null);

        //头像 40 100px 文字 24  字体30
        g2d.setFont(new Font("黑体",Font.PLAIN,30)); //字体、字型、字号
        Color mycolor = Color.black;
        g2d.setColor(mycolor);
        g2d.drawString(emp,164,80);
        g2d.setFont(new Font("黑体",Font.PLAIN,22)); //字体、字型、字号
        Color mycolor1 = new Color(119, 119, 119);
        g2d.setColor(mycolor1);
        g2d.drawString(store,164,130);

        g2d.dispose();// 释放图形上下文使用的系统资源
        return buffImg;
    }

    /**
     * 输出水印图片
     *
     * @param buffImg
     *            图像加水印之后的BufferedImage对象
     * @param savePath
     *            图像加水印之后的保存路径
     */
    public void generateWaterFile(BufferedImage buffImg, String savePath) {

        int temp = savePath.lastIndexOf(".") + 1;
        try {
            ImageIO.write(buffImg, savePath.substring(temp), new File(savePath));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }



    /**
     *
     * @param args
     * @throws IOException
     *             IO异常直接抛出了
     * @author bls
     */
    public static void main(String[] args) throws IOException {

        String sourceFilePath = "C://Users//86177//Desktop//新建文件夹 (11)//wwww.png";
        String waterFilePath = "C://Users//86177//Desktop//新建文件夹 (11)//1-0.jpg";
        String codeFilePath = "C://Users//86177//Desktop//新建文件夹 (11)//7174.png";
        String saveFilePath = "C://Users//86177//Desktop//新建文件夹 (11)//xxxxx.png";
        ImageSynthesis newImageUtils = new ImageSynthesis();
        // 构建叠加层
        BufferedImage buffImg = newImageUtils.watermark(new File(sourceFilePath), new File(waterFilePath),
                new File(codeFilePath),"张三","石家庄店");
        // 输出水印图片
        newImageUtils.generateWaterFile(buffImg, saveFilePath);
    }
}
